//
//  UIViewController+Top.m
//  OCBase
//
//  Created by 侯伟 on 2019/4/16.
//  Copyright © 2019年 侯伟. All rights reserved.
//

#import "UIViewController+Top.h"

@implementation UIViewController (Top)

+ (UIViewController*)topViewController{
    
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (true)
    {
        if ([controller isKindOfClass: [UINavigationController class]])
        {
            UINavigationController *nav = (UINavigationController*)controller;
            controller = nav.visibleViewController;
            
        } else if ([controller isKindOfClass:[UITabBarController class]])
        {
            UITabBarController *tabBarCtl = (UITabBarController*)controller;
            if (tabBarCtl.selectedViewController)
            {
                controller = tabBarCtl.selectedViewController;
            }
        } else if (controller.presentedViewController)
        {
            controller = controller.presentedViewController;
        } else
        {
            break;
        }
    }
    
    return controller;
}

+ (UINavigationController*)currentNavigationController{
    
    UINavigationController *navCtl;
    UIViewController *viewController = [self topViewController];
    if ([viewController isKindOfClass:[UINavigationController class]]){
        navCtl = (UINavigationController *)viewController;
    }else if(viewController.navigationController){
        navCtl = viewController.navigationController;
    }else {
        UIViewController* viewController = UIApplication.sharedApplication.keyWindow.rootViewController;
        if([viewController isKindOfClass:UINavigationController.class]){
            navCtl = (UINavigationController *)viewController;
        }
    }
    return navCtl;
}

-(BOOL)isCurrentViewControllerVisible{
    return (self.isViewLoaded && self.view.window);
}
@end
